package com.xxja.order.order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxja.order.auth.user.pojo.User;
import com.xxja.order.config.interceptor.LoginInterceptor;
import com.xxja.order.config.snowId.IdWorker;
import com.xxja.order.order.mapper.OrderDetailMapper;
import com.xxja.order.order.mapper.OrderMapper;
import com.xxja.order.order.mapper.OrderStatusMapper;
import com.xxja.order.order.pojo.Order;
import com.xxja.order.order.pojo.OrderDetail;
import com.xxja.order.order.pojo.OrderStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderService {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderStatusMapper orderStatusMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderService.class);
    /**
     * 创建订单
     * @param order 订单对象
     * @return 订单编号
     */
    @Transactional
    public Long createOrder(Order order) {
        // 生成orderId
        long orderId = idWorker.nextId();
        // 获取登录用户
        User user = LoginInterceptor.getLoginUser();
        // 初始化数据
        order.setBuyerNick(user.getName());
        order.setBuyerRate(false);
        order.setCreateTime(new Date());
        order.setOrderId(orderId);
        order.setUserId(user.getId());
        // 保存数据
        this.orderMapper.insert(order);
        // 保存订单状态
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(orderId);
        orderStatus.setCreateTime(order.getCreateTime());
        orderStatus.setStatus(1);// 初始状态设为未付款
        this.orderStatusMapper.insert(orderStatus);

        // 订单详情中添加orderId
        order.getOrderDetails().forEach(od -> {
            od.setOrderId(orderId);
        });
        // 保存订单转态使用批量插入功能
        this.orderDetailMapper.insertOrderDetail(order.getOrderDetails());
        LOGGER.debug("生成订单，订单编号：{}，用户id：{}", orderId, user.getId());
        return orderId;
    }

    /**
     * 查询订单
     * @param id
     * @return
     */
    public Order queryById(Long id) {
        // 查询订单
        Order order = this.orderMapper.selectById(id);
        // 查询订单详情
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_id", id);
        List<OrderDetail> details = this.orderDetailMapper.selectList(queryWrapper);
        order.setOrderDetails(details);
        // 查询订单状态
        OrderStatus orderStatus = this.orderStatusMapper.selectById(order.getOrderId());
        order.setStatus(orderStatus.getStatus());
        return order;
    }

    /**
     * 查询订单用户下的所有订单
     * @param page
     * @return
     */
    public IPage<Order> queryUserOrderList(Page page) {
        try {
            // 获取登录用户
            User user = LoginInterceptor.getLoginUser();
            // 查出该用户下的所有订单
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", user.getId());
            Page<Order> record = this.orderMapper.selectPage(page, queryWrapper);
            List<Order> records = record.getRecords();
            records.forEach(od -> {
                OrderStatus orderStatus = this.orderStatusMapper.selectById(od.getOrderId());
                od.setStatus(orderStatus.getStatus());
            });

            return record;
        } catch (Exception e) {
            LOGGER.error("查询订单出错", e);
            return null;
        }
    }

    /**
     * 更改订单状态
     * @param id
     * @param status
     * @return
     */
    @Transactional
    public Boolean updateStatus(Long id, Integer status) {
        OrderStatus record = new OrderStatus();
        record.setOrderId(id);
        record.setStatus(status);
        // 根据状态判断要修改的时间
        switch (status) {
            case 2:
                record.setPaymentTime(new Date());// 付款
                break;
            case 3:
                record.setConsignTime(new Date());// 发货
                break;
            case 4:
                record.setEndTime(new Date());// 确认收获，订单结束
                break;
            case 5:
                record.setCloseTime(new Date());// 交易失败，订单关闭
                break;
            case 6:
                record.setCommentTime(new Date());// 评价时间
                break;
            default:
                return null;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_id", id);
        int count = this.orderStatusMapper.update(record, queryWrapper);
        return count == 1;
    }
}
